package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    @Override
    public User findByUsername(String username) {
        //查询用户基本信息,不包含用户的角色
        User user = userDao.findByUsername(username);
        if(user == null){
            return null;
        }

        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }
    //新增用户
    @Override
    public void add(User user, Integer[] roleIds) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.add(user);
        setUserAndRole(user.getId(),roleIds);
    }

    //设置用户和角色的关联关系
    public void setUserAndRole(Integer userId, Integer[] roleIds) {
        if(roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    //分页查询
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.selectByCondition(queryString);
        List<User> result = page.getResult();
        for (User user : result) {
            user.setPassword(null);
        }
        return new PageResult(page.getTotal(), result);
    }
    //根据id查询
    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    //编辑用户,同时更新用户与角色的关联关系
    @Override
    public void edit(User user, Integer[] roleIds) {
        //根据用户id删除中间表数据(清理原有的关系)
        userDao.deleteAssociation(user.getId());
        //向中间表(t_user_role)插入数据,建立关联关系
        setUserAndRole(user.getId(),roleIds);
        //更新用户的基本信息
        if(user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userDao.edit(user);
    }

    @Override
    public void deleteById(Integer id) {
        userDao.deleteById(id);
    }

    @Override
    public Integer findCountByUsername(String username) {
        return userDao.findCountByUsername(username);
    }

}
